package com.example.jasonrpc.client;

import com.example.jasonrpc.codec.Decoder;
import com.example.jasonrpc.codec.Encoder;
import com.example.jasonrpc.proto.Request;
import com.example.jasonrpc.proto.Response;
import com.example.jasonrpc.proto.ServiceDescriptor;
import com.example.jasonrpc.transport.TransportClient;
import org.apache.commons.io.IOUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * 调用远程服务的代理类
 */
public class RemoteInvoker implements InvocationHandler {
    private Class clazz;
    private Encoder encoder;
    private Decoder decoder;
    private TransportSelector selector;

    public RemoteInvoker(Class clazz, Encoder encoder, Decoder decoder, TransportSelector selector) {
        this.clazz = clazz;
        this.encoder = encoder;
        this.decoder = decoder;
        this.selector = selector;
    }

    @Override
    public Object invoke(Object proxy,
                         Method method,
                         Object[] args) throws Throwable {
        Request request = new Request();
        request.setService(ServiceDescriptor.build(clazz, method));
        request.setParameters(args);

        Response response = invokeRemote(request);
        if (response == null || response.getCode() != 0) {
            throw new IllegalStateException("Fail to invoke remote: " + response);
        }
        return response.getData();
    }

    /**
     * 发送rpc请求给服务端：1.序列化请求数据；2.已建立连接的客户端发送请求；
     * 3.反序列化接收的响应数据
     * @param request
     * @return
     */
    private Response invokeRemote(Request request) {
        TransportClient client = null;
        Response response = new Response();
        try {
            client = selector.select();
            byte[] outBytes = encoder.encode(request);
            InputStream in = client.write(new ByteArrayInputStream(outBytes));
            byte[] inBytes = IOUtils.readFully(in, in.available());
            response = decoder.decode(inBytes, Response.class);
        } catch (IOException e) {
            e.printStackTrace();
            response.setCode(1);
            response.setMessage("RpcClient got error: " + e.getClass() + ", " + e.getMessage());
        } finally {
            if (client != null) {
                selector.release(client);
            }
        }
        return response;
    }
}
